package com.example.note.activity;

import android.Manifest;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import android.text.TextUtils;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import com.example.note.R;
import com.example.note.database.DiaryEntity;
import com.example.note.receiver.ReminderReceiver;
import com.example.note.view.HandwritingView;
import com.example.note.viewmodel.DiaryViewModel;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DiaryEditActivity extends AppCompatActivity {

    public static final String EXTRA_DIARY_ID = "diary_id";

    private MaterialToolbar toolbar;
    private TextInputEditText etTitle, etContent;
    private TextView tvDate, tvTime, tvReminderTime;
    private ImageView ivMood, ivWeather, ivImagePreview;
    private ImageButton btnHandwriting, btnSave, btnSelectMusic, btnPlayMusic, btnUndo, btnClearCanvas;
    private MaterialButton btnAddImage, btnAddEmoji;
    private Switch switchReminder;
    private LinearLayout textInputLayout, handwritingContainer;
    private HandwritingView handwritingView;

    private DiaryViewModel diaryViewModel;
    private DiaryEntity currentDiary;
    private Calendar selectedDateTime, reminderDateTime;
    private String selectedImagePath;
    private String selectedMood = "1"; // 1: happy, 2: sad, 3: neutral
    private String selectedWeather = "1"; // 1: sunny, 2: cloudy, 3: rainy
    private String selectedMusicPath;
    private String currentInputMode = "typing"; // typing 或 handwriting
    private MediaPlayer mediaPlayer;

    private ActivityResultLauncher<Intent> imagePickerLauncher;
    private ActivityResultLauncher<Intent> musicPickerLauncher;
    private ActivityResultLauncher<String[]> permissionLauncher;

    private static final int PERMISSION_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_edit);

        initViews();
        initViewModel();
        initPermissionLauncher();
        initImagePicker();
        initMusicPicker();
        setupListeners();
        loadDiaryData();
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        tvDate = findViewById(R.id.tv_date);
        tvTime = findViewById(R.id.tv_time);
        tvReminderTime = findViewById(R.id.tv_reminder_time);
        ivMood = findViewById(R.id.iv_mood);
        ivWeather = findViewById(R.id.iv_weather);
        ivImagePreview = findViewById(R.id.iv_image_preview);
        btnHandwriting = findViewById(R.id.btn_handwriting);
        btnSave = findViewById(R.id.btn_save);
        btnAddImage = findViewById(R.id.btn_add_image);
        btnAddEmoji = findViewById(R.id.btn_add_emoji);
        btnSelectMusic = findViewById(R.id.btn_select_music);
        btnPlayMusic = findViewById(R.id.btn_play_music);
        btnUndo = findViewById(R.id.btn_undo);
        btnClearCanvas = findViewById(R.id.btn_clear_canvas);
        switchReminder = findViewById(R.id.switch_reminder);
        textInputLayout = findViewById(R.id.text_input_layout);
        handwritingContainer = findViewById(R.id.handwriting_container);
        handwritingView = findViewById(R.id.handwriting_view);

        selectedDateTime = Calendar.getInstance();
        reminderDateTime = Calendar.getInstance();
        updateDateTimeDisplay();
    }

    private void initViewModel() {
        diaryViewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
    }

    private void initPermissionLauncher() {
        permissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    boolean allGranted = true;
                    for (Boolean granted : result.values()) {
                        if (!granted) {
                            allGranted = false;
                            break;
                        }
                    }
                    
                    if (allGranted) {
                        // 权限已授予，可以选择图片
                        openImagePicker();
                    } else {
                        Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void initImagePicker() {
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri imageUri = result.getData().getData();
                        if (imageUri != null) {
                            selectedImagePath = imageUri.toString();
                            ivImagePreview.setImageURI(imageUri);
                            ivImagePreview.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

    private void initMusicPicker() {
        musicPickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri musicUri = result.getData().getData();
                        if (musicUri != null) {
                            try {
                                // 获取持久化权限
                                getContentResolver().takePersistableUriPermission(musicUri, 
                                    Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                Log.d("DiaryEditActivity", "获取持久化权限成功: " + musicUri.toString());
                                
                                selectedMusicPath = musicUri.toString();
                                btnPlayMusic.setVisibility(View.VISIBLE);
                                Toast.makeText(this, "音乐已选择", Toast.LENGTH_SHORT).show();
                            } catch (SecurityException e) {
                                Log.e("DiaryEditActivity", "无法获取持久化权限", e);
                                Toast.makeText(this, "无法获取音乐文件的持久访问权限", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
        );
    }

    private void setupListeners() {
        toolbar.setNavigationOnClickListener(v -> finish());

        btnSave.setOnClickListener(v -> saveDiary());

        btnHandwriting.setOnClickListener(v -> toggleInputMode());

        tvDate.setOnClickListener(v -> showDatePicker());
        tvTime.setOnClickListener(v -> showTimePicker());

        ivMood.setOnClickListener(v -> showMoodSelector());
        ivWeather.setOnClickListener(v -> showWeatherSelector());

        btnAddImage.setOnClickListener(v -> requestImagePermission());
        btnAddEmoji.setOnClickListener(v -> showEmojiSelector());

        // 提醒功能监听器
        switchReminder.setOnCheckedChangeListener((buttonView, isChecked) -> {
            tvReminderTime.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        });

        tvReminderTime.setOnClickListener(v -> showReminderTimePicker());

        // 音乐功能监听器
        btnSelectMusic.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("audio/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            musicPickerLauncher.launch(intent);
        });
        btnPlayMusic.setOnClickListener(v -> toggleMusicPlayback());

        // 手写功能监听器
        btnUndo.setOnClickListener(v -> {
            if (handwritingView != null) {
                handwritingView.undo();
            }
        });

        btnClearCanvas.setOnClickListener(v -> {
            if (handwritingView != null) {
                handwritingView.clearCanvas();
            }
        });
    }

    private void loadDiaryData() {
        long diaryId = getIntent().getLongExtra(EXTRA_DIARY_ID, -1);
        if (diaryId != -1) {
            // 编辑模式
            toolbar.setTitle("编辑日记");
            diaryViewModel.getDiaryById((int) diaryId).observe(this, diary -> {
                if (diary != null) {
                    currentDiary = diary;
                    populateFields(diary);
                }
            });
        } else {
            // 新建模式
            toolbar.setTitle("新建日记");
            currentDiary = new DiaryEntity();
        }
    }

    private void populateFields(DiaryEntity diary) {
        etTitle.setText(diary.getTitle());
        etContent.setText(diary.getContent());

        if (diary.getDate() != null && diary.getTime() != null) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                Date date = dateFormat.parse(diary.getDate() + " " + diary.getTime());
                if (date != null) {
                    selectedDateTime.setTime(date);
                    updateDateTimeDisplay();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        selectedMood = diary.getMood();
        selectedWeather = diary.getWeather();
        updateMoodWeatherDisplay();

        if (!TextUtils.isEmpty(diary.getImagePath())) {
            selectedImagePath = diary.getImagePath();
            ivImagePreview.setImageURI(Uri.parse(selectedImagePath));
            ivImagePreview.setVisibility(View.VISIBLE);
        }

        // 填充提醒信息
        if (diary.isHasReminder() && diary.getReminderTime() > 0) {
            switchReminder.setChecked(true);
            reminderDateTime.setTimeInMillis(diary.getReminderTime());
            updateReminderTimeDisplay();
            tvReminderTime.setVisibility(View.VISIBLE);
        }

        // 填充音乐信息
        if (!TextUtils.isEmpty(diary.getBackgroundMusicPath())) {
            selectedMusicPath = diary.getBackgroundMusicPath();
            btnPlayMusic.setVisibility(View.VISIBLE);
        }

        // 填充输入模式和手写内容
        if (!TextUtils.isEmpty(diary.getInputMode())) {
            currentInputMode = diary.getInputMode();
            updateInputModeDisplay();
            
            // 如果是手写模式且有手写内容，加载手写内容
            if ("handwriting".equals(currentInputMode) && !TextUtils.isEmpty(diary.getHandwritingPath())) {
                loadHandwritingFromFile(diary.getHandwritingPath());
            }
        }
    }

    private void showDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    selectedDateTime.set(Calendar.YEAR, year);
                    selectedDateTime.set(Calendar.MONTH, month);
                    selectedDateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateDateTimeDisplay();
                },
                selectedDateTime.get(Calendar.YEAR),
                selectedDateTime.get(Calendar.MONTH),
                selectedDateTime.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    private void showTimePicker() {
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    selectedDateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    selectedDateTime.set(Calendar.MINUTE, minute);
                    updateDateTimeDisplay();
                },
                selectedDateTime.get(Calendar.HOUR_OF_DAY),
                selectedDateTime.get(Calendar.MINUTE),
                true
        );
        timePickerDialog.show();
    }

    private void showMoodSelector() {
        String[] moods = {"开心", "难过", "平静"};
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("选择心情")
                .setItems(moods, (dialog, which) -> {
                    selectedMood = String.valueOf(which + 1);
                    updateMoodWeatherDisplay();
                })
                .show();
    }

    private void showWeatherSelector() {
        String[] weathers = {"晴天", "多云", "雨天"};
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("选择天气")
                .setItems(weathers, (dialog, which) -> {
                    selectedWeather = String.valueOf(which + 1);
                    updateMoodWeatherDisplay();
                })
                .show();
    }

    private void requestImagePermission() {
        String[] permissions;
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新的媒体权限
            permissions = new String[]{Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            // Android 12 及以下使用传统存储权限
            permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
        }
        
        // 检查权限
        boolean hasPermission = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                hasPermission = false;
                break;
            }
        }
        
        if (hasPermission) {
            // 已有权限，直接选择图片
            openImagePicker();
        } else {
            // 请求权限
            permissionLauncher.launch(permissions);
        }
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        imagePickerLauncher.launch(intent);
    }

    private void updateDateTimeDisplay() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        tvDate.setText(dateFormat.format(selectedDateTime.getTime()));
        tvTime.setText(timeFormat.format(selectedDateTime.getTime()));
    }

    private void updateMoodWeatherDisplay() {
        // 更新心情图标
        switch (selectedMood) {
            case "1":
                ivMood.setImageResource(R.drawable.ic_mood_happy);
                break;
            case "2":
                ivMood.setImageResource(R.drawable.ic_mood_sad);
                break;
            case "3":
                ivMood.setImageResource(R.drawable.ic_mood_neutral);
                break;
        }

        // 更新天气图标
        switch (selectedWeather) {
            case "1":
                ivWeather.setImageResource(R.drawable.ic_weather_sunny);
                break;
            case "2":
                ivWeather.setImageResource(R.drawable.ic_weather_cloudy);
                break;
            case "3":
                ivWeather.setImageResource(R.drawable.ic_weather_rainy);
                break;
        }
    }

    private void saveDiary() {
        String title = etTitle.getText().toString().trim();
        String content = "";
        boolean hasContent = false;
        String handwritingPath = null;

        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "请输入日记标题", Toast.LENGTH_SHORT).show();
            return;
        }

        // 根据当前输入模式检查内容
        if ("handwriting".equals(currentInputMode)) {
            // 手写模式：检查画布是否有内容
            if (handwritingView != null && handwritingView.hasContent()) {
                hasContent = true;
                content = "手写内容"; // 标记为手写内容
                // 保存手写内容为图片
                handwritingPath = saveHandwritingToFile();
            }
        } else {
            // 文本模式：检查文本输入框
            content = etContent.getText().toString().trim();
            hasContent = !TextUtils.isEmpty(content);
        }

        if (!hasContent) {
            Toast.makeText(this, "请输入日记内容", Toast.LENGTH_SHORT).show();
            return;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        currentDiary.setTitle(title);
        currentDiary.setContent(content);
        currentDiary.setDate(dateFormat.format(selectedDateTime.getTime()));
        currentDiary.setTime(timeFormat.format(selectedDateTime.getTime()));
        currentDiary.setMood(selectedMood);
        currentDiary.setWeather(selectedWeather);
        currentDiary.setImagePath(selectedImagePath);
        currentDiary.setHandwritingPath(handwritingPath);
        currentDiary.setHandwritten("handwriting".equals(currentInputMode));
        currentDiary.setTimestamp(System.currentTimeMillis());

        // 保存提醒信息
        currentDiary.setHasReminder(switchReminder.isChecked());
        if (switchReminder.isChecked() && reminderDateTime != null) {
            currentDiary.setReminderTime(reminderDateTime.getTimeInMillis());
            setReminder(reminderDateTime.getTimeInMillis(), title);
        } else {
            currentDiary.setReminderTime(0);
        }

        // 保存音乐信息
        currentDiary.setBackgroundMusicPath(selectedMusicPath);

        // 保存输入模式
        currentDiary.setInputMode(currentInputMode);

        if (currentDiary.getId() == 0) {
            // 新建日记
            diaryViewModel.insert(currentDiary);
        } else {
            // 更新日记
            diaryViewModel.update(currentDiary);
        }

        Toast.makeText(this, "日记保存成功", Toast.LENGTH_SHORT).show();
        finish();
    }

    // 保存手写内容到文件
    private String saveHandwritingToFile() {
        if (handwritingView == null || !handwritingView.hasContent()) {
            return null;
        }

        try {
            // 创建保存目录
            File handwritingDir = new File(getFilesDir(), "handwriting");
            if (!handwritingDir.exists()) {
                handwritingDir.mkdirs();
            }

            // 生成文件名
            String fileName = "handwriting_" + System.currentTimeMillis() + ".png";
            File file = new File(handwritingDir, fileName);

            // 获取手写内容的Bitmap
            Bitmap bitmap = handwritingView.getCanvasBitmap();
            
            // 保存到文件
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();

            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "保存手写内容失败", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    // 从文件加载手写内容
    private void loadHandwritingFromFile(String handwritingPath) {
        if (TextUtils.isEmpty(handwritingPath) || handwritingView == null) {
            return;
        }

        try {
            File file = new File(handwritingPath);
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(handwritingPath);
                if (bitmap != null) {
                    handwritingView.loadFromBitmap(bitmap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "加载手写内容失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void showEmojiSelector() {
        // 使用更兼容的表情列表，移除可能导致乱码的表情
        String[] emojis = {
                "😀", "😃", "😄", "😁", "😆", "😅", "😂", "😊", "😇",
                "🙂", "😉", "😌", "😍", "😘", "😗", "😙", "😚",
                "😋", "😛", "😝", "😜", "😎", "😏", "😒", "😞", 
                "😔", "😟", "😕", "🙁", "😣", "😖", "😫", "😩", 
                "😢", "😭", "😤", "😠", "😡", "😳", "😱", "😨", 
                "😰", "😥", "😓", "🤗", "🤔", "😶", "😐", "😑", 
                "😬", "🙄", "😯", "😦", "😧", "😮", "😲", "😴", 
                "😪", "😵", "😷", "🤒", "🤕", "🤑", "🤠", "😈", 
                "👿", "👹", "👺", "🤡", "💩", "👻", "💀", "👽", 
                "❤️", "💛", "💚", "💙", "💜", "🖤", "💔", "❣️",
                "💕", "💖", "💗", "💘", "💝", "💞", "💟", "☮️",
                "✝️", "☪️", "🕉️", "☸️", "✡️", "🔯", "🕎", "☯️"
        };

        // 创建BottomSheetDialog
        com.google.android.material.bottomsheet.BottomSheetDialog bottomSheetDialog = 
                new com.google.android.material.bottomsheet.BottomSheetDialog(this);
        
        View bottomSheetView = LayoutInflater.from(this)
                .inflate(R.layout.bottom_sheet_emoji_picker, null);
        
        androidx.recyclerview.widget.RecyclerView rvEmojiList = 
                bottomSheetView.findViewById(R.id.rv_emoji_list);
        
        // 设置GridLayoutManager，每行显示6个表情
        androidx.recyclerview.widget.GridLayoutManager gridLayoutManager = 
                new androidx.recyclerview.widget.GridLayoutManager(this, 6);
        rvEmojiList.setLayoutManager(gridLayoutManager);
        
        // 创建表情列表
        java.util.List<String> emojiList = java.util.Arrays.asList(emojis);
        
        // 设置适配器
        com.example.note.adapter.EmojiAdapter emojiAdapter = 
                new com.example.note.adapter.EmojiAdapter(emojiList, emoji -> {
                    insertEmojiToFocusedField(emoji);
                    bottomSheetDialog.dismiss();
                });
        
        rvEmojiList.setAdapter(emojiAdapter);
        
        bottomSheetDialog.setContentView(bottomSheetView);
        bottomSheetDialog.show();
    }

    private void insertEmojiToFocusedField(String emoji) {
        // 获取当前有焦点的输入框
        TextInputEditText focusedEditText = null;
        
        if (etTitle != null && etTitle.hasFocus()) {
            focusedEditText = etTitle;
        } else if (etContent != null && etContent.hasFocus()) {
            focusedEditText = etContent;
        } else {
            // 如果没有焦点，默认插入到内容字段
            focusedEditText = etContent;
        }
        
        if (focusedEditText != null) {
            int cursorPosition = focusedEditText.getSelectionStart();
            String currentText = focusedEditText.getText().toString();
            String newText = currentText.substring(0, cursorPosition) + emoji + currentText.substring(cursorPosition);
            focusedEditText.setText(newText);
            focusedEditText.setSelection(cursorPosition + emoji.length());
        }
    }

    // 保留原方法以保持兼容性
    private void insertEmojiToContent(String emoji) {
        insertEmojiToFocusedField(emoji);
    }

    // 显示提醒时间选择器
    private void showReminderTimePicker() {
        Calendar calendar = Calendar.getInstance();

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                (view, year, month, dayOfMonth) -> {
                    reminderDateTime.set(Calendar.YEAR, year);
                    reminderDateTime.set(Calendar.MONTH, month);
                    reminderDateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                    TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                            (timeView, hourOfDay, minute) -> {
                                reminderDateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
                                reminderDateTime.set(Calendar.MINUTE, minute);
                                updateReminderTimeDisplay();
                            },
                            calendar.get(Calendar.HOUR_OF_DAY),
                            calendar.get(Calendar.MINUTE),
                            true);
                    timePickerDialog.show();
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));

        datePickerDialog.show();
    }

    // 更新提醒时间显示
    private void updateReminderTimeDisplay() {
        if (reminderDateTime != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            tvReminderTime.setText("提醒时间: " + format.format(reminderDateTime.getTime()));
        }
    }

    // 设置系统提醒
    private void setReminder(long timeInMillis, String title) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, ReminderReceiver.class);
        intent.putExtra("title", title);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
                (int) timeInMillis, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        if (alarmManager != null) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
        }
    }

    // 切换音乐播放状态
    private void toggleMusicPlayback() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            btnPlayMusic.setImageResource(R.drawable.ic_play);
        } else if (mediaPlayer != null) {
            mediaPlayer.start();
            btnPlayMusic.setImageResource(R.drawable.ic_pause);
        } else if (!TextUtils.isEmpty(selectedMusicPath)) {
            try {
                mediaPlayer = new MediaPlayer();
                
                // 检查音乐路径格式并设置数据源
                if (selectedMusicPath.startsWith("content://")) {
                    // 使用 content URI
                    mediaPlayer.setDataSource(this, Uri.parse(selectedMusicPath));
                } else {
                    // 使用文件路径
                    mediaPlayer.setDataSource(selectedMusicPath);
                }
                
                mediaPlayer.prepareAsync(); // 使用异步准备
                
                mediaPlayer.setOnPreparedListener(mp -> {
                    mp.start();
                    btnPlayMusic.setImageResource(R.drawable.ic_pause);
                });
                
                mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                    Log.e("DiaryEditActivity", "MediaPlayer错误: what=" + what + ", extra=" + extra);
                    Toast.makeText(this, "音乐播放失败，请检查文件格式", Toast.LENGTH_SHORT).show();
                    return true;
                });

                mediaPlayer.setOnCompletionListener(mp -> {
                    btnPlayMusic.setImageResource(R.drawable.ic_play);
                });
            } catch (Exception e) {
                Log.e("DiaryEditActivity", "设置音乐数据源失败", e);
                e.printStackTrace();
                Toast.makeText(this, "音乐播放失败，请重新选择音乐文件", Toast.LENGTH_SHORT).show();
                
                // 清理失败的MediaPlayer
                if (mediaPlayer != null) {
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            }
        } else {
            Toast.makeText(this, "请先选择音乐文件", Toast.LENGTH_SHORT).show();
        }
    }

    // 更新输入模式显示
    private void updateInputModeDisplay() {
        if ("handwriting".equals(currentInputMode)) {
            btnHandwriting.setImageResource(R.drawable.ic_keyboard);
            // 显示手写画布，隐藏文本输入
            textInputLayout.setVisibility(View.GONE);
            handwritingContainer.setVisibility(View.VISIBLE);
        } else {
            btnHandwriting.setImageResource(R.drawable.ic_handwriting);
            // 显示文本输入，隐藏手写画布
            textInputLayout.setVisibility(View.VISIBLE);
            handwritingContainer.setVisibility(View.GONE);
        }
    }

    // 启用手写输入模式
    private void enableHandwritingMode() {
        // 手写模式的逻辑已在updateInputModeDisplay中处理
    }

    // 启用打字输入模式
    private void enableTypingMode() {
        // 打字模式的逻辑已在updateInputModeDisplay中处理
    }

    // 切换输入模式
    private void toggleInputMode() {
        if ("typing".equals(currentInputMode)) {
            currentInputMode = "handwriting";
            Toast.makeText(this, "已切换到手写模式", Toast.LENGTH_SHORT).show();
        } else {
            currentInputMode = "typing";
            Toast.makeText(this, "已切换到打字模式", Toast.LENGTH_SHORT).show();
        }
        updateInputModeDisplay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}